/**
 *		Licensed to the Apache Software Foundation (ASF) under one
 *     or more contributor license agreements.  See the NOTICE file
 *     distributed with this work for additional information
 *     regarding copyright ownership.  The ASF licenses this file
 *     to you under the Apache License, Version 2.0 (the
 *     "License"); you may not use this file except in compliance
 *     with the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing,
 *     software distributed under the License is distributed on an
 *     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *     KIND, either express or implied.  See the License for the
 *     specific language governing permissions and limitations
 *     under the License.
 *     
 *     Image Resizer Project
 */

package image.resizer.ui;

import image.resizer.Utils;

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.IOException;
import java.util.Locale;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

/**
 * Main Image Resizer UI window.
 * 
 * @author Dudarev Ilya
 */
public class MainResizerWindow {

	private static final String CLASS_NAME = MainResizerWindow.class.getName();
	private static final Logger logger = Logger.getLogger(MainResizerWindow.class.getPackage().getName());
	private static final Level FINER_LEVEL = Level.FINER;
	private static final String LOG_FILE = "ImageResizerUI.log";
	private static final Level DEFAULT_LEVEL = Level.WARNING;
	private static final String LOG_ARG_PREFIX = "loglevel=";
	
	private static final String MAIN_TITLE = "Resizing images";
	private static final String SOURCE_DIR_TITLE = "Source directory";
	private static final String SOURCE_DIR_TOOL_TIP = "The directory, that contains the images, that need to be resized.";
	private static final String TARGET_DIR_TITLE = "Target directory";
	private static final String TARGET_DIR_TOOL_TIP = "The directory for placing resized images.";
	private static final String BROWSE_BUTTON_LABEL = "Browse";
	
	private static final String MAIN_WINDOW_TITLE = "Image Resizer v.0.1b";
	private static final String START_BUTTON_LABEL = "Start";
	private static final String CLOSE_BUTTON_LABEL = "Close";
	private static final String CONFIGURE_BUTTON_LABEL = "Configure";
	private static final String PROGRESS_LABEL = "Progress: ";
	
	private static final String FAILED_TO_START_IMAGE_RESIZER_MSG = "Failed to start Image Resizer application.";
	
	private static ResizerUIConfig config;
	
	public static void main(String[] args) {
		String logParam = null;
		for(String arg : args)
		{
			if(arg !=null & arg.startsWith(LOG_ARG_PREFIX))
			{
				logParam = arg.substring(LOG_ARG_PREFIX.length());
			}
		}
		try
		{
			config = new ResizerUIConfig();
			// Setting locale
			Locale configLocale = config.getUILocale();
			if(!Locale.getDefault().equals(configLocale))
			{
				NLS.resetLocale(configLocale);
			}
		}
		catch (Exception e) {
			// using default locale
		}
		
		try
		{
			// Setting the logger
			Handler[] handlers = logger.getHandlers();
			for(int i = 0 ; i < handlers.length ; i++)
			{
				Handler handler = handlers[i];
				logger.removeHandler(handler);
			}
		      
			Level loglevel = DEFAULT_LEVEL;
			if(!Utils.isEmpty(logParam))
			{
				loglevel = Level.parse(logParam);
			}
			FileHandler handler = new FileHandler(LOG_FILE, true);
			handler.setFormatter(new SimpleFormatter());
			handler.setLevel(loglevel);
			logger.addHandler(handler);
			logger.setLevel(loglevel);
		}
		catch (IOException e) {
			// Nothing to do
		}
		
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.entering(CLASS_NAME, "main", args);
		}
		try
		{
			MainResizerWindow window = new MainResizerWindow();
			window.start();
		}
		catch (Throwable th) {
			logger.logp(Level.SEVERE, CLASS_NAME, "main", "Failed to initiate main window class.", th);
			JOptionPane.showMessageDialog(null, FAILED_TO_START_IMAGE_RESIZER_MSG,
					"Error", JOptionPane.ERROR_MESSAGE);// No NLS
		}
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "main");
		}
	}
	
	private void start()
	{
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.entering(CLASS_NAME, "start");
		}
		EventQueue.invokeLater(
		new Runnable() {
				public void run() {
					JFrame frame = new JFrame(MAIN_WINDOW_TITLE);
					frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
					frame.add(new JLabel(NLS.formatter.getString(MAIN_TITLE)));
					// Paths panel
					GridBagLayout gridBagPathsLayout = new GridBagLayout();
					JPanel pathsPanel = new JPanel(gridBagPathsLayout);
					JLabel sourceDirLabel = new JLabel(NLS.formatter.getString(SOURCE_DIR_TITLE));
					sourceDirLabel.setToolTipText(NLS.formatter.getString(SOURCE_DIR_TOOL_TIP));
					GridBagConstraints pathPanelConstraints = new GridBagConstraints();
					pathPanelConstraints.fill = GridBagConstraints.NONE;
					pathPanelConstraints.weightx = 0.0;
					pathPanelConstraints.insets = new Insets(2, 2, 2, 2);
					pathPanelConstraints.anchor = GridBagConstraints.LINE_START;
					gridBagPathsLayout.setConstraints(sourceDirLabel, pathPanelConstraints);
					pathsPanel.add(sourceDirLabel);
					JTextField sourceTextbox = new JTextField(20);
					sourceTextbox.setText(config.getSourceDirPath());
					sourceTextbox.setToolTipText(NLS.formatter.getString(SOURCE_DIR_TOOL_TIP));
					pathPanelConstraints.weightx = 1.0;
					pathPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
					sourceTextbox.getDocument().addDocumentListener(new TextFieldDocumentListener(sourceTextbox, config, true));
					gridBagPathsLayout.setConstraints(sourceTextbox, pathPanelConstraints);
					pathsPanel.add(sourceTextbox);
					JButton sourceBrowseButton = new JButton(NLS.formatter.getString(BROWSE_BUTTON_LABEL));
					sourceBrowseButton.setToolTipText(NLS.formatter.getString(SOURCE_DIR_TOOL_TIP));
					pathPanelConstraints.weightx = 0.0;
					pathPanelConstraints.fill = GridBagConstraints.NONE;
					BrowseDirectoryActionListener sourceBrowseListener = new BrowseDirectoryActionListener(pathsPanel,sourceTextbox);
					sourceBrowseButton.addActionListener(sourceBrowseListener);
					pathPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
					gridBagPathsLayout.setConstraints(sourceBrowseButton, pathPanelConstraints);
					pathsPanel.add(sourceBrowseButton);
					
					JLabel targetDirLabel = new JLabel(NLS.formatter.getString(TARGET_DIR_TITLE));
					targetDirLabel.setToolTipText(NLS.formatter.getString(TARGET_DIR_TOOL_TIP));
					pathPanelConstraints.gridwidth = 1;
					pathPanelConstraints.weightx = 0.0;
					gridBagPathsLayout.setConstraints(targetDirLabel, pathPanelConstraints);
					pathsPanel.add(targetDirLabel);
					JTextField targetTextbox = new JTextField(20);
					targetTextbox.setText(config.getTargetDirPath());
					targetTextbox.setToolTipText(NLS.formatter.getString(TARGET_DIR_TOOL_TIP));
					pathPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
					pathPanelConstraints.weightx = 1.0;
					targetTextbox.getDocument().addDocumentListener(
							new TextFieldDocumentListener(targetTextbox, config, false));
					gridBagPathsLayout.setConstraints(targetTextbox, pathPanelConstraints);
					pathsPanel.add(targetTextbox);
					JButton targetBrowseButton = new JButton(NLS.formatter.getString(BROWSE_BUTTON_LABEL));
					targetBrowseButton.setToolTipText(NLS.formatter.getString(TARGET_DIR_TOOL_TIP));
					pathPanelConstraints.weightx = 0.0;
					BrowseDirectoryActionListener targetBrowseListener =
						new BrowseDirectoryActionListener(pathsPanel, targetTextbox);
					targetBrowseButton.addActionListener(targetBrowseListener);
					pathPanelConstraints.gridwidth = GridBagConstraints.REMAINDER;
					pathPanelConstraints.fill = GridBagConstraints.NONE;
					gridBagPathsLayout.setConstraints(targetBrowseButton, pathPanelConstraints);
					pathsPanel.add(targetBrowseButton);
					
					// Progress bar
					JProgressBar progress = new JProgressBar(0, 100);
					progress.setStringPainted(true);
					// Buttons panel
					JPanel buttonsPanel = new JPanel();
					GridBagLayout buttonsBagPathsLayout = new GridBagLayout();
					GridBagConstraints buttonsPanelConstraints = new GridBagConstraints();
					buttonsPanelConstraints.fill = GridBagConstraints.NONE;
					buttonsPanelConstraints.weightx = 1.0;
					buttonsPanelConstraints.insets = new Insets(2, 2, 2, 2);
					buttonsPanelConstraints.anchor = GridBagConstraints.CENTER;
					buttonsPanel.setLayout(buttonsBagPathsLayout);
					JButton startButton = new JButton(NLS.formatter.getString(START_BUTTON_LABEL));
					
					JButton closeButton = new JButton(NLS.formatter.getString(CLOSE_BUTTON_LABEL));
					closeButton.addActionListener(new CloseButtonActionListener(frame));
					JButton configureButton = new JButton(NLS.formatter.getString(CONFIGURE_BUTTON_LABEL));
					configureButton.addActionListener(new ConfigureActionListener(frame, config));
					startButton.addActionListener(new StartResizeActionListener(progress, config, new JButton[]{configureButton, startButton}));
					buttonsBagPathsLayout.setConstraints(startButton, buttonsPanelConstraints);
					buttonsPanel.add(startButton);
					buttonsBagPathsLayout.setConstraints(closeButton, buttonsPanelConstraints);
					buttonsPanel.add(closeButton);
					buttonsBagPathsLayout.setConstraints(configureButton, buttonsPanelConstraints);
					buttonsPanel.add(configureButton);
					
					// Progress panel
					JPanel progressPanel = new JPanel();
					GridBagLayout progressBagPathsLayout = new GridBagLayout();
					GridBagConstraints progressPanelConstraints = new GridBagConstraints();
					progressPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
					progressPanelConstraints.weightx = 0.0;
					progressPanelConstraints.insets = new Insets(2, 2, 2, 2);
					progressPanelConstraints.anchor = GridBagConstraints.LINE_END;
					progressPanel.setLayout(progressBagPathsLayout);
					JLabel progressLabel = new JLabel(NLS.formatter.getString(PROGRESS_LABEL));
					progressBagPathsLayout.setConstraints(progressLabel, progressPanelConstraints);
					progressPanelConstraints.weightx = 1.0;
					progressPanelConstraints.anchor = GridBagConstraints.LINE_START;
					progressBagPathsLayout.setConstraints(progress, progressPanelConstraints);
					progressPanel.add(progressLabel);
					progressPanel.add(progress);
					
					frame.add(pathsPanel);
					frame.add(buttonsPanel);
					frame.add(progressPanel);
					
					frame.pack();
					frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
					frame.setVisible(true);
				}
			}
		);
		if(logger.isLoggable(FINER_LEVEL))
		{
			logger.exiting(CLASS_NAME, "start");
		}
	}
}
